package com.hzhh123.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import org.junit.Test;

/**
 * 通道之间数据传输与内存映射文件 transferTo()/transferFrom()
 * 
 * @author hzhh123
 *
 */
public class ChannelTransferDemo {

	/**
	 * 利用通道进行文件复制（非直接缓冲区）
	 */
	@Test
	public void test1() {
		FileInputStream in = null;
		FileOutputStream out = null;
		FileChannel inChannel = null;
		FileChannel outChannel = null;
		try {
			in = new FileInputStream("1.txt");
			out = new FileOutputStream("2.txt");
			inChannel = in.getChannel();
			outChannel = out.getChannel();
			ByteBuffer buf = ByteBuffer.allocate(1024);
			while ((inChannel.read(buf)) != -1) {
				buf.flip();// 切换数据读写模式
				outChannel.write(buf);
				buf.clear();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outChannel != null) {
				try {
					outChannel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inChannel != null) {
				try {
					inChannel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 直接使用缓冲区完成文件复制（内存映射）
	 * @throws IOException 
	 */
	@Test
	public void test2() throws IOException {
		FileChannel inChannel = FileChannel.open(Paths.get("1.txt"), StandardOpenOption.READ);
		FileChannel outChannel=FileChannel.open(Paths.get("3.txt"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW);
		MappedByteBuffer mappedByteBuffer1 = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
		MappedByteBuffer mappedByteBuffer2 = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
		byte[] b=new byte[mappedByteBuffer1.limit()];
		mappedByteBuffer1.get(b);
		mappedByteBuffer2.put(b);
		outChannel.close();
		inChannel.close();
		
	}
	/**
	 * 使用通道传输复制transferFrom/transferTo
	 * @throws IOException
	 */
	@Test
	public void test3() throws IOException {
		FileChannel inChannel = FileChannel.open(Paths.get("1.txt"), StandardOpenOption.READ);
		FileChannel outChannel=FileChannel.open(Paths.get("3.txt"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW);
		//inChannel.transferTo(0, inChannel.size(), outChannel);
		outChannel.transferFrom(inChannel, 0, inChannel.size());
		outChannel.close();
		inChannel.close();
		
	}
}
